// var stat1 = "0";
var ringId = "0";
var roomId = "0";
var memberId = "";
var diagnosisId = "";
var nickName = "";
let headImg = "";
var deptName = "";
var userSign = "";
var ring2ly = "";
var options2 = {};
var tmply = "";
var tmpIp = "";
var tmpYm = "";
var tmpRctid = "";
var tmpRoomId = "";
var consType = "";
var userId = "";
var doctorId = "";
var serverIP = "";
var serverApi = "";
var serverApi3 = "";
var serverApi1 = "";
var socketUrl6 = "";

//loading层

var index;

function startVideo() {
    if (sessionStorage.getItem('tcpLink') === "linking") {
        clearInterval(time1);
        console.log("开始连接。。")
        $("#defaultShowImg").attr("src", "img/inquiry/placeholder2.png")
        // index = layer.load(1);

        let obj = JSON.parse(sessionStorage.getItem('obj'));
        tmply = obj.ly;
        tmpIp = obj.ip;
        tmpYm = obj.yuming;
        tmpRctid = obj.rctid;
        tmpRoomId = obj.roomId;
        consType = obj.fwqbm;
        tmpRctid = obj.ring2rctid;
        doctorId = obj.doctorId;
        userId = obj.userId;
        serverIP = obj.serverIP;
        serverApi = obj.serverApi;
        serverApi3 = obj.serverApi3;
        serverApi1 = obj.serverApi1;
        socketUrl6 = obj.socketUrl6;

        checkUserSign("doctor" + doctorId);

        roomId = obj.roomId;
        loadHuanzheInfo(roomId);


        // qiang1();

        //抢到一个单
        jietingOne(roomId, "1");//普通接听

    }
}

function qiang1() {
    var rid = roomId;
    ring2ly = tmply;
    ring2IP = tmpIp;
    ring2ym = tmpYm;
    ring2rctid = tmpRctid;
    if (ring2ly == "2") {
        serverIP = ring2IP;
        serverApi = "https://" + ring2ym + "/a02";
        serverApi3 = "https://" + ring2ym + "/a03";
        serverApi1 = "https://" + ring2ym + "/a01";
        socketUrl6 = "wss://" + ring2ym + "/wss/websocket";
    }
    // dengMp3.pause();//暂停播放提示音
    // layer.close(qangIndex);
    // qangIndex = "";
    //域外
    if (ring2ly == "2") {
        //医生更换id
        var reqData = {fwqbm: consType, doctorId: doctorId};
        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            url: serverApi + "/zy/findSysDoctorByFwqbmId" + "?" + formatParams(reqData),
            success: function (result) {
                console.log(JSON.stringify(result));
                if (result.code == "200") {
                    doctorId = result.data;
                    userId = userId;

                    tmpRoomId = rid;
                    jietingOne(tmpRoomId, "1");//普通接听


                } else {
                    layer.msg("外部服务器调用失败：" + result.msg);
                }
            },
            error: function (e) {
                console.error("获得外部医生id失败！");
            }
        });
        //域内
    } else {
        jietingOne(roomId, "1");//普通接听
    }
}

var time1 = setInterval('startVideo()', 1000);//轮询执行，5000ms一次


//3、接听一个呼叫

function jietingOne(rid, stat) {
    //视频接通时调用，先创建一个订单
    var reqData0 = {
        memberId: memberId,
        doctorId: doctorId,
        trialDrugId: 55,
        pharmInspectionId: 136,
        ringId: rid,
    };
    $.ajax({
        type: "POST",
        url: serverApi + "/omsring/jietingOne" + "?" + formatParams(reqData0),
    })
    // dengMp3.pause();//暂停播放提示音
    var reqData = {roomid: rid, type: stat};
    if (stat == "2") {
        reqData.types = "1";
    }
    console.log("提交接听：" + JSON.stringify(reqData));
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        url: serverApi + "/omsring/updateOmsRing" + "?" + formatParams(reqData),
        success: function (result) {
            console.log("接听结果：" + JSON.stringify(result));
            var s = result.data;
            if (s != null && s != "") {
                ringId = s.id.trim();//接诊台id
                roomId = s.id.trim();//房间id
                var doctorAid = s.doctorAid;//医生A的id
                var doctorBid = s.doctorBid;//医生B的id(转诊时)
                var historicalPrescription = s.historicalPrescription;//历史处方
                memberId = s.memberId;//患者id
                var mtype = s.mtype;//1问诊,2转诊
                var panelType = s.panelType;//控制台点击来源1小程序2APP3PC
                var pharmId = s.pharmId;//门诊/药店id
                var idcard = s.sid;//患者身份证
                var stat = s.stat;//状态0呼叫等待1已接听2转呼中3已挂断(已拒绝)4等待取消
                var timeaa = s.timeaa;//门诊发起呼叫时间(转诊时为医生A)
                var timebb = s.timebb;//医生A接听时间(转诊时为医生B接听)
                var timecc = s.timecc;//医生A挂断时间(转诊时为医生B挂断)
                console.log("接听结果roomId：" + roomId);
                if (roomId != "") {
                    //加载患者信息
                    //loadHuanzheInfo(ringId);
                    //自动接听，开始视频
                    var options = {
                        sdkAppId: txRtcId,
                        userId: userId,
                        userSig: userSign,
                        roomId: roomId
                    };
                    if (ring2ly == "2") {
                        options2 = options;
                        changeSign();
                    } else {
                        kaishiRTC(options);//域内接听
                    }
                    //xunhuanRingStat1();
                    //$("#video-zanting").show();
                    //$("#video-jieshu").show();

                    setTimeout(function () {
                        // layer.close(index);
                        $("#defaultShow").attr("style", "width: 605px;height: 750px;display:none")
                        $("#linkShow").attr("style", "width: 605px;height: 750px;")
                        console.log("rrrrrrrrrrrrrrrrrrrrrrrrrr")
                        $("#video-grid").children("div").attr("style", "justify-content:center;width:100%;height:750px;");
                    }, 2000);
                    // $("#video-grid").css({"width":winW+"px", "height":winH2+"px", "top":"0px", "left":"0px", "z-index":"9", "position":"fixed"});
                    // $("#video-grid").find("video").css({"width":winW+"px", "height":winH2+"px"});
                    // $("#video-grid").find("video").parent().css("height",winH2+"px");
                    // $("#video-grid").find("video").parent().parent().css("height",winH2+"px");
                }
            }
        },
        error: function (e) {
            console.error("接听一个呼叫失败！");
        }
    });
}

function changeSign() {
    if (ring2ly == "2") {
        options2.sdkAppId = ring2rctid;
        serverIP = ring2IP;
        serverApi = "https://" + ring2ym + "/a02";
        serverApi3 = "https://" + ring2ym + "/a03";
        serverApi1 = "https://" + ring2ym + "/a01";
        socketUrl6 = "wss://" + ring2ym + "/wss/websocket";
    }
    var reqData = {memberId: userId};
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        url: serverApi + "/omsring/genTestUserSig" + "?" + formatParams(reqData),
        success: function (result) {
            var sign3 = result.data;
            if (sign3.length > 0) {
                userSign = sign3;
                options2.userSig = userSign;
                kaishiRTC(options2);
            }
        },
        error: function (e) {
            console.error("更新签名失败！");
        }
    });
}

//4、加载患者信息
var keyiXuanYaodian = 1;

function loadHuanzheInfo(ringId) {
    var reqData = {roomid: ringId};
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        url: serverApi + "/omsring/findUmsMemberReceptionDeskVO" + "?" + formatParams(reqData),
        success: function (result) {
            var ring = result.data;
            if (ring != null && ring != "") {
                memberId = ring.fmemberId;
                doctorId = doctorId;
                diagnosisId = ring.diagnosisId;
                nickName = $.cookie("truename");
                headImg = ring.icon;
                deptName = $.cookie("deptName");
                //发送验证消息
                loadSocket();
                window.setTimeout("javascript:send1();", 900);
                var bcTime1 = window.setInterval(function () {
                    loadSocket();
                    window.setTimeout("javascript:send1();", 900);
                }, 10000);
                console.log("socket验证消息ms11已发送");
            }
        },
        error: function (e) {
            console.error("加载患者信息失败！");
        }
    });
}

//5、获取RTC用户签名
function checkUserSign(uid) {
    var reqData = {memberId: uid};
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        url: serverApi + "/omsring/genTestUserSig" + "?" + formatParams(reqData),
        success: function (result) {
            var sign3 = result.data;
            if (sign3.length > 0) {
                userSign = sign3; //alert(userSign);
            }
        },
        error: function (e) {
            console.error("获取签名失败！");
        }
    });
}

//7、暂停展示
var zantingIndex = "";
var hasZanTing = 0;

function toZanting() {
    var txt = "隐藏图像";
    if (hasZanTing == 1) txt = "恢复图像";
    zantingIndex = layer.confirm(txt + '向对方展示自己画面吗？', {
        btn: ['确定', '取消']
    }, function () {
        // loadSocket();
        window.setTimeout(function () {
            //发送暂停视频socket给小程序
            var content = "暂停视频";
            var conCode = "11";
            if (hasZanTing == 1) {
                content = "恢复视频";
                conCode = "12";
                hasZanTing = 0;
                $("#video-zanting").text("暂停视频");
            } else {
                hasZanTing = 1;
                $("#video-zanting").text("恢复视频");
            }
            var message = "#ms12#m" + memberId + "#ms12#d" + doctorId + "#ms12#" + nickName + "#ms12#" + headImg + "#ms12#" + content + "#ms12#" + conCode + "#ms12#" + diagnosisId + "#ms12#";
            if (!window.WebSocket) {
                console.error("socket连接失败..");
                return;
            }
            if (socket.readyState == WebSocket.OPEN) {
                socket.send(message);
                layer.msg("您已对患者" + content + "画面");
                layer.close(zantingIndex);
            } else {
                console.error("socket连接失败请重试..");
            }
        }, 900);
    }, function () {

    });
}

//7.挂断
function toLeave() {
    sessionStorage.setItem('tcpLink', "stop");
    layer.msg("tcpLink stop.")
    console.log("roomId+++" + roomId)
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        url: serverApi + "/omsring/consultation?roomid=" + roomId,
        success: function (result) {
            if (result.code === 200) {
                console.log(result.data);
                $("#defaultShowImg").attr("src", "img/inquiry/placeholder.png")
                $("#defaultShow").attr("style", "width: 605px;height: 750px;")
                $("#linkShow").attr("style", "width: 605px;height: 750px;display:none")
                // sessionStorage.removeItem('obj');
                sessionStorage.removeItem('memberData');
                $.removeCookie('memberId', {path: '/'});
                $.removeCookie('memberSid', {path: '/'});
                // faGuanbi();
                //发送挂断socket给小程序
                var content = "0";
                var message = "#ms12#m"+memberId+"#ms12#d"+doctorId+"#ms12#"+nickName+"#ms12#"+headImg+"#ms12#"+content+"#ms12#"+8+"#ms12#"+diagnosisId+"#ms12#";
                if(!window.WebSocket){console.error("socket连接失败..");return;}
                if(socket.readyState == WebSocket.OPEN){
                    socket.send(message);
                }else{
                    console.error("socket连接失败请重试..");
                }
                parent.window.location.reload();
            } else {
                alert("请求失败")
            }
        },
        error: function (e) {
            alert("请求失败")
        }
    });
}
function faGuanbi(){
    loadSocket();
    window.setTimeout(function(){
        //发送挂断socket给小程序
        var content = "0";
        var message = "#ms12#m"+memberId+"#ms12#d"+doctorId+"#ms12#"+nickName+"#ms12#"+headImg+"#ms12#"+content+"#ms12#"+8+"#ms12#"+diagnosisId+"#ms12#";
        if(!window.WebSocket){console.error("socket连接失败..");return;}
        if(socket.readyState == WebSocket.OPEN){
            socket.send(message);
        }else{
            console.error("socket连接失败请重试..");
        }

        leave();//离开RTC
        console.log("#shuaxinRTC#");//刷新页面
    },900);
}

/***Socket连接开始***/
var socket = "";
var pictureBottom = 245;

function loadSocket() {
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        socket = new WebSocket(socketUrl6);
        socket.onmessage = function (event) {
            var data = event.data;
            console.log("收到消息：" + data);
            if (data.indexOf("#ms11#") != -1) {
                //收到初始化验证消息
                if (data.indexOf("#dianshi#") != -1) {
                    toXuanzhuan();//小电视旋转270
                } else if (data.indexOf("#teevee#") != -1) {
                    toXZhuanTV();//大电视旋转180
                }
            } else if (data.indexOf("#ms12#") != -1) {
                //收到普通消息
                var res = data.substr(data.indexOf("#ms12#"), data.length).split("#ms12#");
                var name = res[3];
                var head = res[4];
                var content1 = res[5];
                var time = res[res.length - 2];
                var type = res[6];
                if (head == "") head = "image/head1.jpg";
                var str = "";
                if (("d" + doctorId) == res[2]) {
                    //我发出的消息
                    if (type == "5") {
                        str += "<div class='chat-right'>";
                        str += "<div class='chat-right-headimg'><img src='" + headImg + "' sname='" + nickName + "'></div>";
                        str += "<div class='chat-right-time'>" + nickName + "&nbsp;&nbsp;" + time + "</div>";
                        str += "<div class='chat-right-text'>";
                        str += "<i></i><p>您已向 " + $("#merName").text() + " 发送了服务包 <span class=bold onclick='kanchufang()'>【" + content1 + "】</span> 未付费</p>";
                        str += "</div></div>";
                    }
                } else {
                    //对方发给我的消息
                    if (type == "2") {
                        $("#linkShow").append('<div style="width:85px;height:85px;position:absolute;right:15px;bottom:' + pictureBottom + 'px;border:0 #eeeeee solid;">\n' +
                            '        <img style="width:100%;height:100%;" src="' + content1 + '" onclick="picture(this)">\n' +
                            '    </div>');
                        pictureBottom += 100;
                    }
                }
                // $("#chatList").append(str);
                // $("#chatList")[0].scrollTop = $("#chatList")[0].scrollHeight;
            }
        };
        socket.onopen = function (event) {
        };
        socket.onclose = function (event) {
        };
    }
}

function picture(data) {
    parent.parent.layer.open({
        type: 1,
        title: "图片",
        // maxmin: true,
        area: ["600px", "600px"],
        content: '<img style="width:100%;height:auto;" src="' + data.src + '">',
        shadeClose: true,
    });
}

function send1() {
    var message = "#ms11#m" + memberId + "#ms11#d" + doctorId + "#ms11#" + diagnosisId + "#ms11#" + nickName + "#ms11#" + deptName + "#ms11#";//验证消息
    if (!window.WebSocket) {
        console.error("socket连接失败.");
        return;
    }
    if (socket != "" && socket.readyState == WebSocket.OPEN) {
        socket.send(message);
    } else {
        console.error("socket连接失败请重试.");
    }
}
